﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;

namespace SideMan.Converts
{
    [ValueConversion(typeof(string), typeof(FlowDocument))]
    public class DocumentConverter : ConverterMarkupExtension<DocumentConverter>
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
 
            if (value is string rtf)
            {
                FlowDocument document = new FlowDocument();
                var content = Base64Util.Decode2Bytes(System.Convert.ToString(rtf));
                using (var stream = new MemoryStream(content))
                {
                    TextRange range = new TextRange(document.ContentStart, document.ContentEnd);
                    range.Load(stream, DataFormats.XamlPackage);
                }
                return document;
            }

            return null;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is FlowDocument document)
            {
                using (var stream = new MemoryStream())
                {
                    TextRange range = new TextRange(document.ContentStart, document.ContentEnd);
                    range.Save(stream, DataFormats.XamlPackage);
                    return Base64Util.Encode(stream.ToArray());
                }
            }

            return "";
        }
    }

}
